package com.rs.admin.sys.org.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.rs.admin.sys.oauth2.TokenGenerator;
import com.rs.admin.sys.org.entity.UserToken;
import com.rs.admin.sys.org.mapper.UserTokenMapper;
import com.rs.admin.sys.org.service.UserTokenService;

import com.rs.common.utils.result.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hedonglin
 * @since 2017-12-20
 */
@Service
public class UserTokenServiceImpl extends ServiceImpl<UserTokenMapper, UserToken> implements UserTokenService {
    @Autowired
    private UserTokenService userTokenService;

    //过期时间
    @Value("${TOKEN_EXPIRE_TIME}")
    private Long TOKEN_EXPIRE_TIME;

    //默认过期时间
    private Long DEFAULT_TOKEN_EXPIRE_TIME = 43200L;
    /**
     * 为用户创建token
     * @param id  用户id
     * @return
     */
    @Override
    public R createToken(Long id) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + (TOKEN_EXPIRE_TIME==null?DEFAULT_TOKEN_EXPIRE_TIME:TOKEN_EXPIRE_TIME) * 1000);

        //返回状态
        boolean result = false;

        //判断是否生成过token
        UserToken tokenEntity = userTokenService.selectById(id);
        if (tokenEntity==null){
            tokenEntity = new UserToken();
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            tokenEntity.setUserId(id);
            //保存
            result = userTokenService.insertAllColumn(tokenEntity);
        }else {
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            //更新
            result =  userTokenService.updateById(tokenEntity);
        }
        if (result){
            return R.ok("生成token成功").put("token",token).put("expire",expireTime);
        }else {
            return R.error("生成token失败");
        }
    }
}
